<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>imTest</title>
	<link rel="stylesheet" type="text/css" href="/static/layui/css/layui.css" />
	<link rel="stylesheet" type="text/css" href="/static/plugins/webuploader/webuploader.css" />
	<link rel="stylesheet" type="text/css" href="/static/common/common.css" />
	<style type="text/css">
		.receive-message-list{
		    border: 1px solid #1e9fff;
    		width: 900px;	
    		height: 300px;
    		overflow-y: auto;
		}
		.layui-timeline-item{
			margin-top: 10px;		
		}
	</style>
</head>
<body class="body-container">
	<div>
		<fieldset class="layui-elem-field layui-field-title"
			style="margin-top: 20px;">
			<legend>云信im聊天demo</legend>
		</fieldset>
	</div>

	<div>
		<span>appKey：</span> <span id="appKey" th:text="${appKey}"></span>
	</div>

	<div>
		<span>account：</span> <span id="account" th:text="${accountId}"></span>
	</div>

	<div>
		<span>token：</span> <span id="imToken" th:text="${token}"></span>
	</div>
		
	<div style="font-size: 20px;font-weight: 800;">
		<span>im状态：</span> <span id="connectionStatus">....</span>
	</div>

	<div>
		<fieldset class="layui-elem-field layui-field-title"
			style="margin-top: 20px;">
			<legend>发送的消息</legend>
		</fieldset>
		<form class="layui-form" action="">
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">输入信息</label>
					<div class="layui-input-inline" style="width: 480px;">
						<input type="text" name="message" autocomplete="off"
							class="layui-input">
					</div>
				</div>
				<div class="layui-inline">
					<label class="layui-form-label">接收人id</label>
					<div class="layui-input-inline" style="width: 120px;">
						<input type="text" onkeyup="numberFilter(this)" name="receiverId"
							autocomplete="off" class="layui-input" maxlength="10">
					</div>
				</div>
				<div class="layui-inline">
					<button type="button" class="layui-btn layui-btn-normal send-msg-btn">发送消息</button>
				</div>
			</div>
		</form>
	</div>

	<div>
		<fieldset class="layui-elem-field layui-field-title"
			style="margin-top: 20px;">
			<legend>消息列表</legend>
		</fieldset>
		<ul class="layui-timeline receive-message-list">
		</ul>
	</div>
		
	<div style="margin-bottom: 200px;">
		<fieldset class="layui-elem-field layui-field-title"
			style="margin-top: 20px;">
			<legend>离线消息</legend>
		</fieldset>
		<ul class="layui-timeline off-line-message-list">
			
		</ul>
	</div>
	
	

	<script src="/static/jquery/jquery-2.1.1.min.js" type="text/javascript"></script>
	<script src="/static/layui/layui.all.js" type="text/javascript"></script>
	<script src="/static/plugins/im/js/NIM_Web_SDK_v6.4.0.js" type="text/javascript"></script>
	<script src="/static/plugins/im/js/NIM_Web_NIM_v6.4.0.js" type="text/javascript"></script>
	<script src="/static/common/common.js" type="text/javascript"></script>
	<script type="text/javascript">
		$(document).ready(function() {
			var appKey = document.getElementById("appKey").innerHTML;
			var account = document.getElementById("account").innerHTML;
			var token = document.getElementById("imToken").innerHTML;
			initNim(appKey, account, token);
		})

		// 发送消息
		$(document).on('click', '.send-msg-btn', function() {
			var message = $("input[name='message']").val();
			if (!message) {
				layer.msg("消息不能为空");
				return false;
			}
			console.log(message);
			var receiverId = $("input[name='receiverId']").val();
			if (!receiverId) {
				layer.msg("接收人不能为空");
				return false;
			}
			nimSendMsg(message, receiverId)
		})
		
		// 发送消息
		function nimSendMsg(msg, to) {
			$.ajax({
				url : '/imTest/sendMsg',
				type : 'POST',
				data : {
					'msg' : msg,
					'to' : to
				},
				success : function(res) {
					console.log(res);
					if (res.code == 200) {
						$("input[name='message']").val("");
					}
				},
				error : function(data) {

				}
			});
		}
		
		//收到消息
		function initReceiveMsg(msg) {
			var html = "";
			if(msg.flow=="out"){		
				html += '<li class="layui-timeline-item" style="margin-left: 500px;">';
				html += '<i class="layui-icon layui-timeline-axis" style="color: #1e9fff;"></i>';
				html += '<div class="layui-timeline-content layui-text">';
				html += '<h3 class="layui-timeline-title">'+commonDateFormat(msg.time,"yyyy-MM-dd hh:mm:ss")+'</h3>';
				// 发出去的
				html += '<p>发出消息：'+msg.text+'</p>';	
				html += '</div>';
				html += '</li>';	
			}else if(msg.flow=="in"){
				html += '<li class="layui-timeline-item">';
				html += '<i class="layui-icon layui-timeline-axis"></i>';
				html += '<div class="layui-timeline-content layui-text">';
				html += '<h3 class="layui-timeline-title">'+commonDateFormat(msg.time,"yyyy-MM-dd hh:mm:ss")+'</h3>';
				// 收到的
				html += '<p>收到消息：'+msg.text+'</p>';	
				html += '</div>';
				html += '</li>';	
			}
			$(".receive-message-list").append(html);
			var receiveMessage = $(".receive-message-list");		
			receiveMessage[0].scrollTop = receiveMessage[0].scrollHeight;
		}
		
		// 离线消息
		function initOffLineMessage(msg){
			var html = "";
			for (let index = 0; index < msg.length; index++) {
				var msgInfo = msg[index];	
				html += '<li class="layui-timeline-item">';	
				html += '<i class="layui-icon layui-timeline-axis"></i>';
				html += '<div class="layui-timeline-content layui-text">';
				html += '<h3 class="layui-timeline-title">'+commonDateFormat(msgInfo.time,"yyyy-MM-dd hh:mm:ss")+'</h3>';
				// 收到的	
				html += '<p>收到消息：'+msgInfo.text+'</p>';	
				html += '</div>';
				html += '</li>';
			}
			$(".off-line-message-list").append(html);
		}
		
		function initNim(appKey, account, token) {
			var data = {};
			// 注意这里, 引入的 SDK 文件不一样的话, 你可能需要使用 SDK.NIM.getInstance 来调用接口
			/* var nim = NIM.getInstance({
				// debug: true,
				appKey : appKey,
				account : account,
				token : token,
				// privateConf: {}, // 私有化部署方案所需的配置
				onconnect : onConnect,
				onwillreconnect : onWillReconnect,
				ondisconnect : onDisconnect,
				onerror : onError
			}); */
			var nim = NIM.getInstance({
				// 初始化SDK
				// debug: true
				appKey : appKey,
				account : account,
				token : token,	
				onconnect : onConnect,
				onerror : onError,
				onwillreconnect : onWillReconnect,
				ondisconnect : onDisconnect,
				// 多端登录
				onloginportschange : onLoginPortsChange,
				// 用户关系
				onblacklist : onBlacklist,
				onsyncmarkinblacklist : onMarkInBlacklist,
				onmutelist : onMutelist,
				onsyncmarkinmutelist : onMarkInMutelist,
				// 好友关系
				onfriends : onFriends,
				onsyncfriendaction : onSyncFriendAction,
				// 用户名片
				onmyinfo : onMyInfo,
				onupdatemyinfo : onUpdateMyInfo,
				onusers : onUsers,
				onupdateuser : onUpdateUser,
				onrobots : onRobots,
				// 群组
				onteams : onTeams,
				onsynccreateteam : onCreateTeam,
				onteammembers : onTeamMembers,
				onsyncteammembersdone : onSyncTeamMembersDone,
				onupdateteammember : onUpdateTeamMember,
				// 会话
				onsessions : onSessions,
				onupdatesession : onUpdateSession,
				// 消息
				onroamingmsgs : onRoamingMsgs,
				onofflinemsgs : onOfflineMsgs,
				onmsg : onMsg,
				// 系统通知
				onofflinesysmsgs : onOfflineSysMsgs,
				onsysmsg : onSysMsg,
				onupdatesysmsg : onUpdateSysMsg,
				onsysmsgunread : onSysMsgUnread,
				onupdatesysmsgunread : onUpdateSysMsgUnread,
				onofflinecustomsysmsgs : onOfflineCustomSysMsgs,
				oncustomsysmsg : onCustomSysMsg,
				// 同步完成
				onsyncdone : onSyncDone
			});

			function onConnect() {
				console.log('连接成功');
				// layer.msg('im聊天,连接成功');
				$("#connectionStatus").text("连接成功......");
			}
			function onWillReconnect(obj) {
				// 此时说明 `SDK` 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
				console.log('即将重连');
				console.log(obj.retryCount);
				console.log(obj.duration);
				$("#connectionStatus").text("即将重连......");
			}
			function onDisconnect(error) {
				// 此时说明 `SDK` 处于断开状态, 开发者此时应该根据错误码提示相应的错误信息, 并且跳转到登录页面
				console.log('丢失连接');
				$("#connectionStatus").text("丢失连接......");
				console.log(error);
				if (error) {
					switch (error.code) {
					// 账号或者密码错误, 请跳转到登录页面并提示错误
					case 302:
						break;
					// 被踢, 请提示错误后跳转到登录页面
					case 'kicked':
						break;
					default:
						break;
					}
				}
			}
			function onError(error) {
				console.log(error);
			}

			function onLoginPortsChange(loginPorts) {
				console.log('当前登录帐号在其它端的状态发生改变了', loginPorts);
			}

			function onBlacklist(blacklist) {
				console.log('收到黑名单', blacklist);
				data.blacklist = nim.mergeRelations(data.blacklist, blacklist);
				data.blacklist = nim.cutRelations(data.blacklist,
						blacklist.invalid);
				refreshBlacklistUI();
			}
			function onMarkInBlacklist(obj) {
				console.log(obj);
				console.log(obj.account + '被你在其它端' + (obj.isAdd ? '加入' : '移除')
						+ '黑名单');
				if (obj.isAdd) {
					addToBlacklist(obj);
				} else {
					removeFromBlacklist(obj);
				}
			}
			function addToBlacklist(obj) {
				data.blacklist = nim.mergeRelations(data.blacklist, obj.record);
				refreshBlacklistUI();
			}
			function removeFromBlacklist(obj) {
				data.blacklist = nim.cutRelations(data.blacklist, obj.record);
				refreshBlacklistUI();
			}
			function refreshBlacklistUI() {
				// 刷新界面
			}
			function onMutelist(mutelist) {
				console.log('收到静音列表', mutelist);
				data.mutelist = nim.mergeRelations(data.mutelist, mutelist);
				data.mutelist = nim.cutRelations(data.mutelist,
						mutelist.invalid);
				refreshMutelistUI();
			}
			function onMarkInMutelist(obj) {
				console.log(obj);
				console.log(obj.account + '被你' + (obj.isAdd ? '加入' : '移除')
						+ '静音列表');
				if (obj.isAdd) {
					addToMutelist(obj);
				} else {
					removeFromMutelist(obj);
				}
			}
			function addToMutelist(obj) {
				data.mutelist = nim.mergeRelations(data.mutelist, obj.record);
				refreshMutelistUI();
			}
			function removeFromMutelist(obj) {
				data.mutelist = nim.cutRelations(data.mutelist, obj.record);
				refreshMutelistUI();
			}
			function refreshMutelistUI() {
				// 刷新界面
			}

			function onFriends(friends) {
				console.log('收到好友列表', friends);
				data.friends = nim.mergeFriends(data.friends, friends);
				data.friends = nim.cutFriends(data.friends, friends.invalid);
				refreshFriendsUI();
			}
			function onSyncFriendAction(obj) {
				console.log(obj);
				switch (obj.type) {
				case 'addFriend':
					console
							.log('你在其它端直接加了一个好友' + obj.account + ', 附言'
									+ obj.ps);
					onAddFriend(obj.friend);
					break;
				case 'applyFriend':
					console
							.log('你在其它端申请加了一个好友' + obj.account + ', 附言'
									+ obj.ps);
					break;
				case 'passFriendApply':
					console.log('你在其它端通过了一个好友申请' + obj.account + ', 附言'
							+ obj.ps);
					onAddFriend(obj.friend);
					break;
				case 'rejectFriendApply':
					console.log('你在其它端拒绝了一个好友申请' + obj.account + ', 附言'
							+ obj.ps);
					break;
				case 'deleteFriend':
					console.log('你在其它端删了一个好友' + obj.account);
					onDeleteFriend(obj.account);
					break;
				case 'updateFriend':
					console.log('你在其它端更新了一个好友', obj.friend);
					onUpdateFriend(obj.friend);
					break;
				}
			}
			function onAddFriend(friend) {
				data.friends = nim.mergeFriends(data.friends, friend);
				refreshFriendsUI();
			}
			function onDeleteFriend(account) {
				data.friends = nim.cutFriendsByAccounts(data.friends, account);
				refreshFriendsUI();
			}
			function onUpdateFriend(friend) {
				data.friends = nim.mergeFriends(data.friends, friend);
				refreshFriendsUI();
			}
			function refreshFriendsUI() {
				// 刷新界面
			}

			function onMyInfo(user) {
				console.log('收到我的名片', user);
				data.myInfo = user;
				updateMyInfoUI();
			}
			function onUpdateMyInfo(user) {
				console.log('我的名片更新了', user);
				data.myInfo = NIM.util.merge(data.myInfo, user);
				updateMyInfoUI();
			}
			function updateMyInfoUI() {
				// 刷新界面
			}
			function onUsers(users) {
				console.log('收到用户名片列表', users);
				data.users = nim.mergeUsers(data.users, users);
			}
			function onUpdateUser(user) {
				console.log('用户名片更新了', user);
				data.users = nim.mergeUsers(data.users, user);
			}
			function onRobots(robots) {
				console.log('收到机器人列表', robots);
				data.robots = robots;
			}
			function onTeams(teams) {
				console.log('群列表', teams);
				data.teams = nim.mergeTeams(data.teams, teams);
				onInvalidTeams(teams.invalid);
			}
			function onInvalidTeams(teams) {
				data.teams = nim.cutTeams(data.teams, teams);
				data.invalidTeams = nim.mergeTeams(data.invalidTeams, teams);
				refreshTeamsUI();
			}
			function onCreateTeam(team) {
				console.log('你创建了一个群', team);
				data.teams = nim.mergeTeams(data.teams, team);
				refreshTeamsUI();
				onTeamMembers({
					teamId : team.teamId,
					members : owner
				});
			}
			function refreshTeamsUI() {
				// 刷新界面
			}
			function onTeamMembers(teamId, members) {
				console.log('群id', teamId, '群成员', members);
				var teamId = obj.teamId;
				var members = obj.members;
				data.teamMembers = data.teamMembers || {};
				data.teamMembers[teamId] = nim.mergeTeamMembers(
						data.teamMembers[teamId], members);
				data.teamMembers[teamId] = nim.cutTeamMembers(
						data.teamMembers[teamId], members.invalid);
				refreshTeamMembersUI();
			}
			function onSyncTeamMembersDone() {
				console.log('同步群列表完成');
			}
			function onUpdateTeamMember(teamMember) {
				console.log('群成员信息更新了', teamMember);
				onTeamMembers({
					teamId : teamMember.teamId,
					members : teamMember
				});
			}
			function refreshTeamMembersUI() {
				// 刷新界面
			}

			function onSessions(sessions) {
				console.log('收到会话列表', sessions);
				data.sessions = nim.mergeSessions(data.sessions, sessions);
				updateSessionsUI();
			}
			function onUpdateSession(session) {
				console.log('会话更新了', session);
				data.sessions = nim.mergeSessions(data.sessions, session);
				updateSessionsUI();
			}
			function updateSessionsUI() {
				// 刷新界面
			}

			function onRoamingMsgs(obj) {
				console.log('漫游消息', obj);
				pushMsg(obj.msgs);
			}
			function onOfflineMsgs(obj) {
				console.log('离线消息', obj);
				initOffLineMessage(obj.msgs);
				pushMsg(obj.msgs);	
			}
			function onMsg(msg) {
				console.log('收到消息', msg.scene, msg.type, msg);
				// 收到消息	
				initReceiveMsg(msg);
				pushMsg(msg);
			}
			function pushMsg(msgs) {
				if (!Array.isArray(msgs)) {
					msgs = [ msgs ];
				}
				var sessionId = msgs[0].sessionId;
				data.msgs = data.msgs || {};
				data.msgs[sessionId] = nim
						.mergeMsgs(data.msgs[sessionId], msgs);
			}

			function onOfflineSysMsgs(sysMsgs) {
				console.log('收到离线系统通知', sysMsgs);
				pushSysMsgs(sysMsgs);
			}
			function onSysMsg(sysMsg) {
				console.log('收到系统通知', sysMsg)
				pushSysMsgs(sysMsg);
			}
			function onUpdateSysMsg(sysMsg) {
				pushSysMsgs(sysMsg);
			}
			function pushSysMsgs(sysMsgs) {
				data.sysMsgs = nim.mergeSysMsgs(data.sysMsgs, sysMsgs);
				refreshSysMsgsUI();
			}
			function onSysMsgUnread(obj) {
				console.log('收到系统通知未读数', obj);
				data.sysMsgUnread = obj;
				refreshSysMsgsUI();
			}
			function onUpdateSysMsgUnread(obj) {
				console.log('系统通知未读数更新了', obj);
				data.sysMsgUnread = obj;
				refreshSysMsgsUI();
			}
			function refreshSysMsgsUI() {
				// 刷新界面
			}
			function onOfflineCustomSysMsgs(sysMsgs) {
				console.log('收到离线自定义系统通知', sysMsgs);
			}
			function onCustomSysMsg(sysMsg) {
				console.log('收到自定义系统通知', sysMsg);
			}

			function onSyncDone() {
				console.log('同步完成');
			}
		}
	</script>
</body>
</html>